<template>
  <list-group
    :dataList.sync="tableData"
    :loading="loading"
    prop="creditor"
    listHeight="calc(100% - 48px)"
    :defaultSize="defaultListSize"
    @saveHandler="saveHandler"
    @delHandler="delHandler"
    @addHandler="addHandler"
    @page-handler="getTableData"
    @change="getTableData()"
  >
    <template v-slot:toolBar>
      <input type="checkbox" v-model="unpaidOnly" @change="getTableData()" />{{
        $t('liability.unpaidOnly')
      }}
    </template>
    <template v-slot:left="{ item, index }">
      <el-form
        :model="item"
        class="l-h-1-6em"
        label-width="60px"
        :rules="rules"
        :ref="'form1' + index"
      >
        <span v-show="!item.inEdit">
          <div :title="item.creditor" class="text-overflow">
            {{ item.creditor }}
          </div>
        </span>
        <el-form-item
          prop="creditor"
          v-show="item.inEdit === true"
          :rules="rules.creditor"
          class="margin-left-xs-60px"
        >
          <el-autocomplete
            class="w-130px"
            v-model="item.creditor"
            :fetch-suggestions="getNameTextList"
            :placeholder="$t('common.pleaseInput')"
            :trigger-on-focus="true"
            :clearable="true"
            @input="validateProp('creditor', index)"
          >
          <template slot-scope="{ item }">
            <div class="autocompelete-item-container">
              <div class="autocompelete-label" :title="item.value">{{item.value}}</div>
              <i class="iconfont icon-close autocompelete-close" @click.stop="deleteNameTextHandler(item.id)" />
            </div>
          </template>
          </el-autocomplete>
        </el-form-item>
      </el-form>
    </template>
    <template v-slot:middle="{ item, index }">
      <el-form
        :model="item"
        class="l-h-1-6em"
        label-width="60px"
        :rules="rules"
        :ref="'form2' + index"
      >
        <span class="text-info" v-show="item.inEdit !== true">{{
          $t('common.amount')
        }}</span>
        <span v-show="item.inEdit !== true">{{
          parseFloat(item.amount).toFixed(2)
        }}</span>
        <el-form-item
          prop="amount"
          :rules="rules.amount"
          :label="$t('common.amount')"
          v-show="item.inEdit === true"
        >
          <el-input
            v-model="item.amount"
            class="w-130px"
            :precision="2"
            :step="0.1"
          ></el-input>
        </el-form-item>
        <div v-show="item.inEdit !== true">
          <span class="text-info">{{ dateFormat(item.date) }}</span>
          <span class="text-info">{{
            item.actualRepaymentDate ? $t('liability.repaid') : $t('liability.unpaid')
          }}</span>
        </div>
        <el-form-item
          prop="date"
          :rules="rules.date"
          :label="$t('liability.borrow')"
          v-show="item.inEdit === true"
        >
          <el-date-picker
            v-model="item.date"
            class="w-130px"
            :picker-options="pickerOptions"
            v-show="item.inEdit"
            type="date"
          ></el-date-picker>
        </el-form-item>
        <el-form-item
          prop="actualRepaymentDate"
          :rules="rules.actualRepaymentDate"
          :label="$t('liability.repay')"
          v-show="item.inEdit === true"
        >
          <el-date-picker
            v-model="item.actualRepaymentDate"
            class="w-130px"
            :picker-options="pickerOptions"
            v-show="item.inEdit"
            type="date"
          ></el-date-picker>
        </el-form-item>
      </el-form>
    </template>
  </list-group>
</template>
<script>
import {
  queryLiabilitiesList,
  upsertLiabilities,
  deleteLiabilities,
  upsertNameText,
  queryNameTextList,
  deleteNameText
} from '@/assets/api'
import { formatDate } from '@/assets/utils/commonUtil'
import ListGroup from '@/components/common/listGroup/Index.vue'
import validationUtil from '@/assets/utils/validationUtil'
const BLUR = 'blur'
export default {
  data () {
    return {
      tableData: {},
      loading: false,
      unpaidOnly: true,
      pickerOptions: { disabledDate: time => time.getTime() >= Date.now() },
      defaultListSize: 10,
      autoCompeleteQueryStr: '',
      autoCompeleteCB: {},
      rules: {
        creditor: [
          {
            required: true,
            message: this.$t('validationMessage.inputRequired'),
            trigger: BLUR
          }
        ],
        amount: [
          {
            required: true,
            message: this.$t('validationMessage.inputRequired'),
            trigger: BLUR
          },
          {
            validator: validationUtil.isFloat,
            trigger: BLUR
          }
        ],
        date: [
          {
            required: true,
            message: this.$t('validationMessage.inputRequired'),
            trigger: BLUR
          }
        ]
      }
    }
  },
  mounted () {
    this.getTableData()
  },
  components: { ListGroup },
  methods: {
    getTableData (limit = this.defaultListSize, offset = 0) {
      if (limit !== this.defaultListSize) { this.defaultListSize = limit }
      this.loading = true
      if (this.tableData.list) { this.tableData.list.splice(0, this.tableData.list.length) }
      queryLiabilitiesList({ unpaidOnly: this.unpaidOnly, limit: limit, offset: offset }).then(
        res => {
          this.tableData = res.data
          this.loading = false
        },
        () => {
          this.loading = false
        }
      )
    },
    delHandler (index) {
      this.loading = true
      deleteLiabilities({ id: this.tableData.list[index].id }).then(res => {
        this.$message({ type: 'success', message: this.$t('common.deleted') })
        this.getTableData()
        this.$emit('updated')
      })
    },
    saveHandler (index) {
      this.$refs['form1' + index].validate(valid1 => {
        this.$refs['form2' + index].validate(valid => {
          if (valid1 && valid) {
            this.loading = true
            upsertLiabilities(this.tableData.list[index]).then(
              res => {
                this.getTableData()
                this.$emit('updated')
              },
              () => {
                this.getTableData()
              }
            )
            upsertNameText({ text: this.tableData.list[index].creditor, type: 'creditor' })
          }
        })
      })
    },
    addHandler () {
      this.$set(this.tableData.list[0], 'date', new Date())
    },
    dateFormat (date) {
      return formatDate(date, 'yyyy-MM-dd')
    },
    getNameTextList (queryStr, cb) {
      if (queryStr !== null) {
        this.autoCompeleteQueryStr = queryStr
      }
      if (cb) {
        this.autoCompeleteCB = cb
      }
      this.autoCompeleteQueryStr = this.autoCompeleteQueryStr || ''
      queryNameTextList({ type: 'creditor', searchText: this.autoCompeleteQueryStr }).then(
        res => {
          const result = res.data.map(item => { item.value = item.text; return item })
          this.autoCompeleteCB(result)
        },
        () => {}
      )
    },
    deleteNameTextHandler (id) {
      deleteNameText({ id: id }).then(res => {
        this.getNameTextList(null, null)
        this.$message({
          type: 'success',
          message: this.$t('common.deleted')
        })
      })
    },
    validateProp (prop, index) {
      this.$refs['form1' + index].validateField(prop)
    }
  }
}
</script>
